package com.jiangcheng.utils;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;

import com.google.common.collect.Maps;

/**
 *
 * <p>
 * PropertiesUtil 静态内部类实现单例模式读取配置文件
 * 静态内部类既能保证线程安全也能保证懒加载
 * <p>
 *
 * @author <a href="mailto:yangkj@corp.21cn.com">yangkj</a>
 * @version
 * @since 2016年8月29日
 */
public class PropertiesUtil2 {

    private static Map<String, String> proMap = Maps.newHashMap();

    private static class PropertiesInstance {
        private static final PropertiesUtil2 props = new PropertiesUtil2();
    }

    public static PropertiesUtil2 getInstance() {
        return PropertiesInstance.props;
    }

    public Map<String, String> getPropMap() {
        return proMap;
    }

    private PropertiesUtil2() {
        proMap = readProperties();
    }

    /**
     * 去读properties文件的内容，保存到Map中
     *
     * @param propsName
     * @return
     */
    @SuppressWarnings({ "rawtypes" })
    private static Map<String, String> readProperties() {
        Properties props = new Properties();
        try {
            InputStream in = PropertiesUtil2.class.getClassLoader().getResourceAsStream("kafka/kafka.properties");
            props.load(in);
            Enumeration en = props.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String value = props.getProperty(key);
                proMap.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return proMap;
    }

    public static void main(String[] args) {
        PropertiesUtil2 props01 = PropertiesUtil2.getInstance();
        PropertiesUtil2 props02 = PropertiesUtil2.getInstance();
        System.out.println(props01 == props02);

        //String testString = "零Ⅲ壹壹872陆7844";
        String testString = "test";
        for (String key : props01.getPropMap().keySet()) {
            if (testString.contains(key)) {
                testString = testString.replace(key, props01.getPropMap().get(key));
            }
        }
        System.out.println(testString);
    }
}